import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Http } from '@angular/http';
import { LeftSidebarService } from '../sidebar/left-sidebar-service';
import { MatDatepickerModule } from '@angular/material';
import { Moment } from 'moment';
import * as moment from 'moment';
import { BaseComponet } from '../BaseComponet';
import { Subscription } from 'rxjs';

declare var $: any;
@Component({
    selector: 'app-user-management',
    templateUrl: './user-management.component.html',
    styleUrls: ['./user-management.component.css']
})
export class UserManagementComponent extends BaseComponet implements OnInit {
    public isOnShow = true;
    public pageNo: number;
    public pageSize: number;
    public orderBy: String;
    public orderType: String;
    public searchKeywords: String;
    public total: number;
    public totalPages: number;
    public users: any[];
    public checkedUserIds: any[];
    public checkedAll = false;
    public menus: any[];
    public showAdd = false;
    public showDelete = false;
    public showModify = false;
    public showLock = false;
    public showUnlock = false;
    public toAddUsername: String;
    public toAddPassword: String;
    public toAddRealname: String;
    public toAddNickname: String;
    public toAddEmail: String;
    public toAddCellphone: String;
    public toAddBirthday: Date;
    public toAddGender: String;
    public toAddPortraitUrl: String;
    public toModifyUserId: String;
    public toModifyUsername: String;
    public toModifyPassword: String;
    public toModifyRealname: String;
    public toModifyNickname: String;
    public toModifyEmail: String;
    public toModifyCellphone: String;
    public toModifyGender: String;
    public toModifyIsLocked: String;
    public toModifyBirthday: Date;
    public toModifyPortraitUrl: String;
    public minPageNo: number;
    public minPageSize: number;
    public minOrderBy: String = '';
    public minOrderType: String = '';
    public minSearchKeywords: String = '';
    public minTotal: number;
    public minTotalPages: number;
    public minPageUserId: String;
    public userJobRolesUserName: String;
    public jobUserRoles: any[];
    public checkedUserJobRoleIds: any[];
    public checkedAllUserJobRoles: boolean;
    public showUserJobRoles = false;
    public showDeleteUserJobRoles = false;
    public menuChangeSubscription: Subscription;
    constructor(
        public routerInfo: ActivatedRoute,
        public http: Http,
        public router: Router,
        public leftSidebarService: LeftSidebarService
    ) {
        super();
    }
    switchButtons() {
        console.log('switchButtons()');
        this.menus = JSON.parse(sessionStorage.getItem('menus'));
        if (this.menus.indexOf('manager:user.back.add') > -1) {
            this.showAdd = true;
        } else {
            this.showAdd = false;
        }
        if (this.menus.indexOf('manager:user.back.modify') > -1) {
            this.showModify = true;
        } else {
            this.showModify = false;
        }
        if (this.menus.indexOf('manager:user.back.delete-by-ids') > -1) {
            this.showDelete = true;
        } else {
            this.showDelete = false;
        }
        if (this.menus.indexOf('manager:user.back.lock') > -1) {
            this.showLock = true;
        } else {
            this.showLock = false;
        }
        if (this.menus.indexOf('manager:user.back.unlock') > -1) {
            this.showUnlock = true;
        } else {
            this.showUnlock = false;
        }
        if (
            this.menus.indexOf(
                'manager:job.back.manage-user-jobs-roles.query'
            ) > -1
        ) {
            this.showUserJobRoles = true;
        } else {
            this.showUserJobRoles = false;
        }
        if (
            this.menus.indexOf('manager:job.back.manage-role-jobs.delete') > -1
        ) {
            this.showDeleteUserJobRoles = true;
        } else {
            this.showDeleteUserJobRoles = false;
        }
    }
    ngOnDestroy() {
        this.isOnShow = false;
        console.log('ngOnDestroy()');
        $('.popover').remove();
        this.menuChangeSubscription.unsubscribe();
    }
    ngOnInit() {
        this.switchButtons();
        this.menuChangeSubscription = this.leftSidebarService.menusChange.subscribe(
            command => {
                this.switchButtons();
            }
        );
        // $('#to-add-birthday').datepicker({
        //     language: 'zh-CN',
        //     autoclose: true, // 选中之后自动隐藏日期选择框
        //     clearBtn: true, // 清除按钮
        //     todayBtn: false, // 今日按钮
        //     format: 'yyyy-mm-dd' // 日期格式，详见 http://bootstrap-datepicker.readthedocs.org/en/release/options.html#format
        // });
        // $('#to-modify-birthday').datepicker({
        //     language: 'zh-CN',
        //     autoclose: true, // 选中之后自动隐藏日期选择框
        //     clearBtn: true, // 清除按钮
        //     todayBtn: false, // 今日按钮
        //     format: 'yyyy-mm-dd' // 日期格式，详见 http://bootstrap-datepicker.readthedocs.org/en/release/options.html#format
        // });
        $('[data-toggle="popover"]').popover();
        // $(document).on('show.bs.modal', '.modal', function () {
        //   $(this).draggable();
        //   $(this).css('overflow-y', 'scroll');
        //   // 防止出现滚动条，出现的话，你会把滚动条一起拖着走的
        // });
        this.routerInfo.params.subscribe((params: Params) => {
            this.pageNo = params['pageNo'];
            this.pageSize = params['pageSize'];
            this.orderBy = params['orderBy'];
            this.orderType = params['orderType'];
            this.searchKeywords = params['searchKeywords'];
            if (this.orderBy == null) {
                this.orderBy = '';
            }
            if (this.orderType == null) {
                this.orderType = '';
            }
            if (this.searchKeywords == null) {
                this.searchKeywords = '';
            }
            if (this.pageNo == null) {
                this.pageNo = 1;
            } else {
                this.pageNo = parseInt(params['pageNo'], 10);
            }
            if (this.pageSize == null) {
                this.pageSize = parseInt(localStorage.getItem('pageSize'), 10);
                if (this.pageSize == null || isNaN(this.pageSize)) {
                    this.pageSize = 30;
                }
            } else {
                localStorage.setItem('pageSize', '' + this.pageSize);
            }
            this.displayData();
        });
    }
    displayData() {
        this.checkedUserIds = [];
        this.checkedAll = false;
        this.showLoading();
        this.http
            .get(
                '/user/back/user/page' +
                    '/search-' +
                    this.searchKeywords.toString() +
                    '/order-by-' +
                    this.orderBy +
                    '/order-type-' +
                    this.orderType +
                    '/page-no/' +
                    this.pageNo +
                    '/page-size/' +
                    this.pageSize
            )
            .map(result => result.json())
            .subscribe(
                result => {
                    if (this.isOnShow) {
                        this.hideLoading();
                    }
                    this.users = result.list;
                    this.total = result.total;
                    this.totalPages = result.totalPages;
                    this.orderBy = result.orderBy;
                    this.orderType = result.orderType;
                },
                error => {
                    // this.router.navigate(['dashboard']);
                }
            );
    }
    sort(orderBy) {
        if (this.orderBy === orderBy) {
            if (this.orderType === 'asc') {
                this.orderType = 'desc';
            } else {
                this.orderType = 'asc';
            }
        } else {
            this.orderBy = orderBy;
        }
        this.router.navigate([
            'user-management/' +
                this.pageNo +
                '/' +
                this.pageSize +
                '/' +
                this.orderBy +
                '/' +
                this.orderType +
                '/' +
                this.searchKeywords.toString()
        ]);
    }
    clearKeywords() {
        this.searchKeywords = '';
    }
    setPageSize(pageSize) {
        this.pageNo = 1;
        this.pageSize = pageSize;
        localStorage.setItem('pageSize', '' + this.pageSize);
        this.router.navigate([
            'user-management/' +
                this.pageNo +
                '/' +
                this.pageSize +
                '/' +
                this.orderBy +
                '/' +
                this.orderType +
                '/' +
                this.searchKeywords.toString()
        ]);
    }
    goToPage(pageNo) {
        this.pageNo = pageNo;
        this.router.navigate([
            'user-management/' +
                this.pageNo +
                '/' +
                this.pageSize +
                '/' +
                this.orderBy +
                '/' +
                this.orderType +
                '/' +
                this.searchKeywords.toString()
        ]);
    }
    toAdd() {
        $('#addModal').modal('show');
    }
    add() {
        if (!this.toAddUsername) {
            alert('用户名为必填');
            return;
        }
        if (!this.toAddRealname) {
            alert('真实姓名为必填');
            return;
        }
        this.showLoadingMsg('正在提交数据……');
        // this.toAddBirthday = $('#to-add-birthday').val();
        this.http
            .post('/user/back/user/', {
                username: this.toAddUsername,
                password: this.toAddPassword,
                realname: this.toAddRealname,
                nickname: this.toAddNickname,
                email: this.toAddEmail,
                cellphone: this.toAddCellphone,
                birthday:
                    this.toAddBirthday == null
                        ? null
                        : moment(this.toAddBirthday).format('YYYY-MM-DD'),
                gender: this.toAddGender,
                portraitUrl: this.toAddPortraitUrl
            })
            .map(result => result.json())
            .subscribe(
                result => {
                    this.hideLoading();
                    alert('添加成功');
                    $('#addModal').modal('hide');
                    this.displayData();
                },
                err => {
                    this.hideLoading();
                }
            );
    }
    checkAll() {
        if (this.checkedAll === false) {
            this.checkedAll = true;
            this.checkedUserIds = [];
            for (let i = 0; i < this.users.length; i++) {
                this.checkedUserIds.push(this.users[i].userId);
            }
            $('.user-list').prop('checked', true);
        } else {
            this.checkedAll = false;
            this.checkedUserIds = [];
            $('.user-list').prop('checked', false);
        }
    }
    check() {
        this.checkedUserIds = [];
        if ($('.user-list').length === $('.user-list:checked').length) {
            this.checkedAll = true;
        } else {
            this.checkedAll = false;
        }
        const checkedUserIds = this.checkedUserIds;
        $('.user-list:checked').each(function() {
            checkedUserIds.push($(this).val());
        });
    }
    toDelete() {
        if (this.checkedUserIds.length <= 0) {
            alert('请先选中需要删除的帐号！');
            return;
        }
        if (confirm('确定删除选中的帐号吗？')) {
            this.http
                .delete(
                    '/user/back/user/by-ids/' + this.checkedUserIds.join('-')
                )
                .map(result => result.json())
                .subscribe(
                    result => {
                        alert(result.message);
                        this.displayData();
                    },
                    error => {
                        this.displayData();
                    }
                );
        }
    }
    toModify() {
        if ($('.user-list:checked').length > 1) {
            alert('一次只能修改一个帐号！');
            return;
        }
        if ($('.user-list:checked').length === 0) {
            alert('请选择需要修改的帐号！');
            return;
        }
        const userId = $('.user-list:checked').val();
        for (let i = 0; i < this.users.length; i++) {
            if (this.users[i].userId === userId) {
                this.toModifyUserId = this.users[i].userId;
                this.toModifyUsername = this.users[i].username;
                this.toModifyRealname = this.users[i].realname;
                this.toModifyNickname = this.users[i].nickname;
                this.toModifyEmail = this.users[i].email;
                this.toModifyCellphone = this.users[i].cellphone;
                this.toModifyGender = this.users[i].gender;
                this.toModifyPortraitUrl = this.users[i].portraitUrl;
                // this.toModifyIsLocked = this.users[i].isLocked;
                this.toModifyBirthday =
                    this.users[i].birthday == null
                        ? null
                        : moment(this.users[i].birthday, 'YYYY-MM-DD').toDate();
                // $('#to-modify-birthday').datepicker(
                //     'setDate',
                //     this.users[i].birthday
                // );
            }
        }
        $('#modifyModal').modal('show');
    }
    modify() {
        this.showLoadingMsg('正在提交数据……');
        this.http
            .put('/user/back/user/' + this.toModifyUserId, {
                userId: this.toModifyUserId,
                username: this.toModifyUsername,
                password: this.toModifyPassword,
                realname: this.toModifyRealname,
                nickname: this.toModifyNickname,
                email: this.toModifyEmail,
                cellphone: this.toModifyCellphone,
                gender: this.toModifyGender,
                portraitUrl: this.toModifyPortraitUrl,
                // isLocked: this.toModifyIsLocked,
                birthday:
                    this.toModifyBirthday == null
                        ? null
                        : moment(this.toModifyBirthday).format('YYYY-MM-DD')
            })
            .map(result => result.json())
            .subscribe(
                result => {
                    this.hideLoading();
                    alert(result.message);
                    $('#modifyModal').modal('hide');
                    this.displayData();
                },
                error => {
                    this.hideLoading();
                }
            );
    }
    lock(userId) {
        this.http
            .put('/user/back/user/' + userId + '/lock', {})
            .map(result => result.json())
            .subscribe(
                result => {
                    alert(result.message);
                    this.displayData();
                },
                error => {}
            );
    }
    unlock(userId) {
        this.http
            .put('/user/back/user/' + userId + '/unlock', {})
            .map(result => result.json())
            .subscribe(
                result => {
                    alert(result.message);
                    this.displayData();
                },
                error => {}
            );
    }
    manageUserJobRoles(userId, userName) {
        $('#jobUserRolesModal').modal('show');
        this.minPageUserId = userId;
        this.userJobRolesUserName = userName;
        this.minPageNo = 1;
        this.minPageSize = parseInt(localStorage.getItem('minPageSize'), 10);
        if (this.minPageSize == null || isNaN(this.minPageSize)) {
            this.minPageSize = 10;
        }
        this.displayMinData();
    }
    setMinPageSize(pageSize) {
        this.minPageNo = 1;
        this.minPageSize = pageSize;
        localStorage.setItem('minPageSize', pageSize);
        this.displayMinData();
    }
    goToMinPage(pageNo) {
        this.minPageNo = pageNo;
        this.displayMinData();
    }
    clearMinKeywords() {
        this.minSearchKeywords = '';
    }
    displayMinData() {
        $('#minLoading').show();
        this.http
            .get(
                '/user/back/job/page/user-' +
                    this.minPageUserId +
                    '/search-' +
                    this.minSearchKeywords +
                    '/order-by-' +
                    this.minOrderBy +
                    '/order-type-' +
                    this.minOrderType +
                    '/page-no/' +
                    this.minPageNo +
                    '/page-size/' +
                    this.minPageSize
            )
            .map(result => result.json())
            .subscribe(
                result => {
                    $('#minLoading').hide();
                    this.minPageNo = result.pageNo;
                    this.minPageSize = result.pageSize;
                    this.minTotal = result.total;
                    this.jobUserRoles = result.list;
                    this.minTotalPages = result.totalPages;
                    this.minOrderBy = result.orderBy;
                    this.minOrderType = result.orderType;
                },
                error => {}
            );
    }
    minSort(orderBy) {
        if (this.minOrderBy === orderBy) {
            if (this.minOrderType === 'asc') {
                this.minOrderType = 'desc';
            } else {
                this.minOrderType = 'asc';
            }
        } else {
            this.minOrderBy = orderBy;
        }
        this.displayMinData();
    }
    checkAllUserJobRoles() {
        if (this.checkedAllUserJobRoles === false) {
            this.checkedAllUserJobRoles = true;
            this.checkedUserJobRoleIds = [];
            for (let i = 0; i < this.jobUserRoles.length; i++) {
                this.checkedUserJobRoleIds.push(
                    this.jobUserRoles[i].otherResults.id
                );
            }
            $('.job-list').prop('checked', true);
        } else {
            this.checkedAllUserJobRoles = false;
            this.checkedUserJobRoleIds = [];
            $('.job-list').prop('checked', false);
        }
    }
    checkUserJobRole() {
        this.checkedUserJobRoleIds = [];
        if ($('.job-list').length === $('.job-list:checked').length) {
            this.checkedAllUserJobRoles = true;
        } else {
            this.checkedAllUserJobRoles = false;
        }
        const checkedUserJobRoleIds = this.checkedUserJobRoleIds;
        $('.job-list:checked').each(function() {
            checkedUserJobRoleIds.push($(this).val());
        });
    }
    toDeleteUserJobRoles() {
        if (this.checkedUserJobRoleIds.length <= 0) {
            alert('请先选中需要删除的角色！');
            return;
        }
        if (confirm('确定删除选中的角色吗？')) {
            this.http
                .delete(
                    '/user/back/job/by-ids/' +
                        this.checkedUserJobRoleIds.join('-')
                )
                .map(result => result.json())
                .subscribe(
                    result => {
                        alert(result.message);
                        this.checkedAllUserJobRoles = false;
                        this.checkedUserJobRoleIds = [];
                        this.displayMinData();
                    },
                    error => {
                        this.displayMinData();
                    }
                );
        }
    }
}
